<template>
  <view class="exposure-page">
    <!-- 帖子列表 -->
    <scroll-view 
      class="post-list" 
      scroll-y="true" 
      @scrolltolower="loadMore"
      refresher-enabled="true"
      @refresherrefresh="onRefresh"
      :refresher-triggered="refreshing"
    >
      <view 
        v-for="post in postList" 
        :key="post.id" 
        class="post-item" 
        @click="goToDetail(post.id)"
      >
        <!-- 用户信息 -->
        <view class="user-info">
          <image 
            :src="post.users.avatar_url || '/static/default-avatar.png'" 
            class="avatar"
          ></image>
          <view class="user-detail">
            <text class="nickname">{{ post.users.nickname || '用户' }}</text>
            <text class="time">{{ formatTime(post.created_at) }}</text>
          </view>
        </view>

        <!-- 帖子内容 -->
        <view class="content">
          <text>{{ post.content }}</text>
        </view>

        <!-- 图片展示 -->
        <view v-if="post.images && post.images.length > 0" class="images-grid">
          <image 
            v-for="(img, index) in post.images.slice(0, 9)" 
            :key="index"
            :src="getFullImageUrl(img)"
            class="post-image"
            :class="getImageClass(post.images.length)"
            mode="aspectFill"
            @click.stop="previewImage(post.images, index)"
          ></image>
        </view>

        <!-- 操作按钮 -->
        <view class="actions">
          <view class="action-item" @click.stop="toggleLike(post)">
            <text class="action-icon" :class="post.is_liked ? 'liked' : ''">❤️</text>
            <text class="count">{{ post.like_count || 0 }}</text>
          </view>
          <view class="action-item" @click.stop="goToDetail(post.id)">
            <text class="action-icon">💬</text>
            <text class="count">{{ post.comment_count || 0 }}</text>
          </view>
          <view class="action-item" @click.stop="sharePost(post)">
            <text class="action-icon">🔗</text>
            <text class="count">{{ post.share_count || 0 }}</text>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view class="loading" v-if="loading">
        <text>加载中...</text>
      </view>
      <view class="no-more" v-if="noMore && postList.length > 0">
        <text>没有更多了</text>
      </view>
      <view class="empty" v-if="!loading && postList.length === 0">
        <text>暂无曝光信息</text>
      </view>
    </scroll-view>

    <!-- 右下角发布按钮 -->
    <view class="fab-btn" @click="goToPublish">
      <text class="fab-icon">+</text>
    </view>
  </view>
</template>

<script>
import api from '@/utils/api.js'

export default {
  data() {
    return {
      postList: [],
      currentPage: 1,
      pageSize: 10,
      loading: false,
      refreshing: false,
      noMore: false
    }
  },
  onLoad() {
    this.loadPosts()
  },
  onShow() {
    // 从发布页面返回时刷新列表
    if (this.shouldRefresh) {
      this.onRefresh()
      this.shouldRefresh = false
    }
  },
  methods: {
    // 加载帖子列表
    async loadPosts(refresh = false) {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const page = refresh ? 1 : this.currentPage
        const response = await api.request({
          url: `/exposure/posts?page=${page}&pageSize=${this.pageSize}`,
          method: 'GET'
        })
        
        if (response.success) {
          const { posts, pagination } = response.data
          
          if (refresh) {
            this.postList = posts
            this.currentPage = 1
            this.noMore = false
          } else {
            this.postList = [...this.postList, ...posts]
          }
          
          this.currentPage = pagination.current_page + 1
          this.noMore = pagination.current_page >= pagination.total_pages
        }
      } catch (error) {
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      this.refreshing = true
      await this.loadPosts(true)
    },
    
    // 上拉加载更多
    loadMore() {
      if (!this.noMore && !this.loading) {
        this.loadPosts()
      }
    },
    
    // 点赞/取消点赞
    async toggleLike(post) {
      try {
        const response = await api.request({
          url: `/exposure/posts/${post.id}/like`,
          method: 'POST'
        })
        if (response.success) {
          post.is_liked = response.data.liked
          post.like_count += response.data.liked ? 1 : -1
        }
      } catch (error) {
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },
    
    // 分享帖子
    async sharePost(post) {
      try {
        // 记录分享统计
        await api.request({
          url: `/exposure/posts/${post.id}/share`,
          method: 'POST'
        })
        
        // 更新分享配置
        this.setShareConfig({
          title: '曝光台 - ' + (post.content.slice(0, 30) + (post.content.length > 30 ? '...' : '')),
          path: `/pages/exposure/detail?id=${post.id}`,
          imageUrl: post.images?.[0] ? this.getFullImageUrl(post.images[0]) : '/static/logo.png'
        })
        
        // 微信小程序中触发分享需要调用系统分享功能
        // #ifdef MP-WEIXIN
        this.triggerShare()
        // #endif
        
        // #ifdef APP-PLUS
        uni.share({
          provider: 'weixin',
          scene: 'WXSceneSession',
          type: 0,
          href: `/pages/exposure/detail?id=${post.id}`,
          title: '曝光台 - ' + (post.content.slice(0, 30) + '...'),
          summary: post.content,
          success() {
            post.share_count += 1
          }
        })
        // #endif
        
      } catch (error) {
        uni.showToast({
          title: '分享失败',
          icon: 'none'
        })
      }
    },
    
    // 预览图片
    previewImage(images, current) {
      const urls = images.map(img => this.getFullImageUrl(img))
      uni.previewImage({
        urls,
        current
      })
    },
    
    // 跳转到发布页面
    goToPublish() {
      uni.navigateTo({
        url: '/pages/exposure/publish'
      })
    },
    
    // 跳转到详情页面
    goToDetail(postId) {
      uni.navigateTo({
        url: `/pages/exposure/detail?id=${postId}`
      })
    },
    
    // 获取完整图片URL
    getFullImageUrl(imagePath) {
      if (!imagePath) return ''
      if (imagePath.startsWith('http')) return imagePath
      return api.getBaseURL().replace('/api/v1', '') + imagePath
    },
    
    // 根据图片数量获取样式类名
    getImageClass(count) {
      if (count === 1) return 'single'
      if (count === 2) return 'double'
      if (count === 4) return 'four'
      return 'multiple'
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '刚刚'
      
      const time = new Date(timeStr)
      if (isNaN(time.getTime())) {
        return '刚刚'
      }
      
      const now = new Date()
      const diff = now - time
      
      if (diff < 60 * 1000) {
        return '刚刚'
      } else if (diff < 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 1000)) + '分钟前'
      } else if (diff < 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 60 * 1000)) + '小时前'
      } else if (diff < 7 * 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前'
      } else {
        return time.toLocaleDateString()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.exposure-page {
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

.post-list {
  height: 100vh;
  padding-bottom: 120rpx;
}

.post-item {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  
  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    margin-right: 20rpx;
  }
  
  .user-detail {
    .nickname {
      display: block;
      font-size: 30rpx;
      color: #333;
      margin-bottom: 8rpx;
    }
    
    .time {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.content {
  font-size: 30rpx;
  color: #333;
  line-height: 1.6;
  margin-bottom: 20rpx;
}

.images-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.post-image {
  border-radius: 8rpx;
  
  &.single {
    width: 400rpx;
    height: 300rpx;
  }
  
  &.double {
    width: calc(50% - 5rpx);
    height: 200rpx;
  }
  
  &.four {
    width: calc(50% - 5rpx);
    height: 150rpx;
  }
  
  &.multiple {
    width: calc(33.33% - 7rpx);
    height: 150rpx;
  }
}

.actions {
  display: flex;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .action-item {
    display: flex;
    align-items: center;
    margin-right: 60rpx;
    color: #666;
    font-size: 28rpx;
    
    .action-icon {
      margin-right: 8rpx;
      font-size: 32rpx;
      
      &.liked {
        filter: brightness(1.2) saturate(1.5);
      }
    }
  }
}

.loading, .no-more, .empty {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}

.fab-btn {
  position: fixed;
  right: 30rpx;
  bottom: 30rpx;
  width: 120rpx;
  height: 120rpx;
  background-color: #007AFF;
  border-radius: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(0, 122, 255, 0.3);
  z-index: 999;
  
  .fab-icon {
    color: #fff;
    font-size: 48rpx;
    font-weight: 300;
    line-height: 1;
  }
  
  &:active {
    transform: scale(0.95);
    transition: transform 0.1s;
  }
}
</style>